#!/usr/bin/env python3
"""
通过Flask应用执行数据库迁移
"""

import os
import sys

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.utils.mysql_db import get_db_connection

def migrate():
    app = create_app()
    
    with app.app_context():
        conn = get_db_connection()
        cursor = conn.cursor()
        
        try:
            # 检查字段是否已存在
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'report_runs' 
                AND COLUMN_NAME = 'output_formats'
            """)
            
            if cursor.fetchone():
                print("字段 output_formats 已存在，跳过迁移")
                return
            
            # 添加字段
            print("添加 output_formats 字段到 report_runs 表...")
            cursor.execute("""
                ALTER TABLE report_runs 
                ADD COLUMN output_formats JSON DEFAULT NULL COMMENT '本次运行的输出格式列表（临时覆盖）' 
                AFTER params
            """)
            
            # 更新现有记录
            print("更新现有记录，设置默认值...")
            cursor.execute("""
                UPDATE report_runs 
                SET output_formats = JSON_ARRAY('html') 
                WHERE output_formats IS NULL
            """)
            
            conn.commit()
            print("迁移完成！")
            
        except Exception as e:
            conn.rollback()
            print(f"迁移失败: {e}")
            raise
        finally:
            cursor.close()
            conn.close()

if __name__ == '__main__':
    migrate()
